package com.zrb.mobile;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

//import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.hhpm.lib.swipelistviewex.SwipeMenu;
import com.hhpm.lib.swipelistviewex.SwipeMenuCreator;
import com.hhpm.lib.swipelistviewex.SwipeMenuItem;
import com.hhpm.lib.xlist.PullToRefreshSwipeMenuListView;
import com.hhpm.lib.xlist.PullToRefreshSwipeMenuListView.IXListViewListener;
import com.hhpm.lib.xlist.PullToRefreshSwipeMenuListView.OnMenuItemClickListener;
/*import com.hhpm.lib.swipelistview.SwipeMenu;
import com.hhpm.lib.swipelistview.SwipeMenuCreator;
import com.hhpm.lib.swipelistview.SwipeMenuItem;
import com.hhpm.lib.swipelistview.SwipeMenuListView.OnMenuItemClickListener;*/
import com.loopj.android.http.RequestParams;
import com.zrb.discover.Discover_pubishmoneyActivity;
import com.zrb.discover.Discover_publishprojectActivity;
import com.zrb.mobile.adapter.UsermyPublishAdapter;
import com.zrb.mobile.adapter.model.BaseEvent;
import com.zrb.mobile.adapter.model.FavorEvent;
import com.zrb.mobile.adapter.model.MessageEvent;
import com.zrb.mobile.adapter.model.UserPublishDto;
import com.zrb.mobile.adapter.model.IntentionDto;
/*import com.zrb.mobile.ui.SwipeMenuListViewEx;*/
import com.zrb.mobile.ui.PullToRefreshSwipeMenuListViewEx;
import com.zrb.mobile.ui.onLoadMoreListener;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.Constants;
import com.zrb.mobile.utility.ProgressDialogEx;
import com.zrb.mobile.utility.Tip;
import com.zrb.mobile.utility.ZrbRestClient;
import com.zrb.mobile.utility.ZrbRestClient.HttpResponseListener;

import de.greenrobot.event.EventBus;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

public class User_my_publish extends BaseActivity implements OnClickListener,
		OnItemClickListener, IXListViewListener {

	UsermyPublishAdapter usermyPublishAdapter;
	private PullToRefreshSwipeMenuListViewEx mListView;
	// private List<Intention> list;
	// int curPageindex=0;
	int currentPage=1;
	Handler myhandler = new Handler();
	private long maxId = 1;
	private enum ActionType{
 		LoadData,DeleteIntent
	}
	
	ActionType curAction;
	int curEditPostion;
    Tip progTip;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.message_home_activity2);
		
		EventBus.getDefault().register(this);
		//registerBoradcastReceiver1();
		initView();
		initRestClient();
		showloading();
		myhandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				//mListView.setRefreshing(true);
				mListView.startRefresh();
 			 
			}
		}, 200);
	}

	 @Override
	protected void onDestroy() {
	    super.onDestroy();
	        // Unregister
	    EventBus.getDefault().unregister(this);
	    //unregisterReceiver(mBroadcastReceiver1);
	}
 	 
	void initRestClient(){
		
		if(null==mZrbRestClient){
 			mZrbRestClient=new  ZrbRestClient(this);
			mZrbRestClient.setOnhttpResponseListener(new HttpResponseListener() {
				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
 				   CommonUtil.showToast(arg0, User_my_publish.this);
 				     switch(curAction){
 				       case LoadData:
 				    	  if (currentPage > 1)  mListView.stopLoadMore();
 		  				  else
 		  					mListView.setRefreshComplete();//  hideloading();
 				    	 break;
 				       case DeleteIntent:
 				    	   break;
 				     }
 				   
				}

				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					// loadingview.Hide();
					String results = new String(arg2);
					 hideloading();
					//CommonUtil.InfoLog("url", results);
  					if(curAction==ActionType.DeleteIntent){
						try {
							JSONObject jsonObject2 = new JSONObject(results);
							int retCode= jsonObject2.getInt("res");
							if(retCode==1) {
 								usermyPublishAdapter.removeAt(curEditPostion);
					 			usermyPublishAdapter.notifyDataSetChanged();
							}	
 							CommonUtil.showToast(retCode==1 ? "删除成功":"删除失败", User_my_publish.this);
 						}
						catch (JSONException e) {
	 						 CommonUtil.showToast( R.string.error_serverdata_loadfail, User_my_publish.this);
						}
 						return;
					}
 				    if (currentPage > 1) {mListView.hideloading();}//mListView.hideloading();
	  				else
	  					mListView.setRefreshComplete(); 
					try {
						Gson gson = new Gson();
						UserPublishDto tmpDto = gson.fromJson(results, UserPublishDto.class);
						if (tmpDto.res == 1) {
							if(currentPage>1) mListView.checkloadMore(CommonUtil.getSize(tmpDto.data));
							if (tmpDto.data != null&& tmpDto.data.size() > 0) {
 								usermyPublishAdapter.setCurDatas(tmpDto.data,currentPage> 1);
	 							usermyPublishAdapter.notifyDataSetChanged();
							} else {
								CommonUtil.showToast(String.format("暂无%1$s信息~~", currentPage == 1 ? "": "更多"),
										            User_my_publish.this);
							}
						} else
							CommonUtil.showToast(tmpDto.msg, User_my_publish.this);
					} catch (Exception e) {
						CommonUtil.showToast( R.string.error_serverdata_loadfail, User_my_publish.this);
					}
				}
			});
			
		}
	}
 	
	/**
	 * 初始化UI
	 */
	private void initView() {

		View v = findViewById(R.id.include_top);
		((TextView) v.findViewById(R.id.txt_title)).setText("我的发布");
		View lefticon = this.findViewById(R.id.title_left_root);
		lefticon.setOnClickListener(this);
		mListView = (PullToRefreshSwipeMenuListViewEx) findViewById(R.id.discover_list_view);
		mListView.setPagesize(10);

		mListView.setOnItemClickListener(this);// 点击事件
 
		usermyPublishAdapter = new UsermyPublishAdapter(this, new ArrayList<IntentionDto>());
		
	/*	
		mListView.initAdapter(usermyPublishAdapter);
		mListView.setOnLoadMoreListener(this);*/
		// listview.setAdapter(usermyPublishAdapter);
		
		mListView.initAdapter(usermyPublishAdapter);
	    mListView.setPullRefreshEnable(true);
	    mListView.setPullLoadEnable(false);
	    mListView.setXListViewListener(this);
	   
		initlistview();
	}

	private void initlistview() {
		// step 1. create a MenuCreator
		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				// create "open" item
				
				SwipeMenuItem editItem = new SwipeMenuItem(User_my_publish.this);
				// set item background
				editItem.setBackground(new ColorDrawable(Color.parseColor("#999999")));
				// set item width
				editItem.setWidth(CommonUtil.dp2px(User_my_publish.this, 90));
				// set a icon
				editItem.setIcon(R.drawable.bianji);
				editItem.setTitle("编辑");
				editItem.setTitleSize(15);
				editItem.setTitleColor(Color.parseColor("#ffffff"));
				// add to menu
				menu.addMenuItem(editItem);
				// create "delete" item
				SwipeMenuItem deleteItem = new SwipeMenuItem(User_my_publish.this);
				// set item background
				deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
						0x3F, 0x25)));
				// set item width
				deleteItem.setWidth(CommonUtil.dp2px(User_my_publish.this, 70));
				// set a icon
				//deleteItem.setIcon(R.drawable.ic_delete);
				deleteItem.setTitle("删除");
				deleteItem.setTitleSize(15);
				deleteItem.setTitleColor(Color.parseColor("#ffffff"));
				// add to menu
				menu.addMenuItem(deleteItem);
				
				
			}
		};
		// set creator
		mListView.setMenuCreator(creator);

		// step 2. listener item click event
		mListView.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public void onMenuItemClick(final int position, SwipeMenu menu, int index) {
				// ApplicationInfo item = mAppList.get(position);
				// CommonUtil.showToast(position+"", getActivity());
				
				curEditPostion=position;
				switch(index){
				  case 0:
					  myhandler.postDelayed(new Runnable() {
							@Override
							public void run() {
								// TODO Auto-generated method stub
								IntentionDto  curDto= usermyPublishAdapter.getAt(position);
								Gson gson = new Gson();  
							    String strObj = gson.toJson(curDto);  
							    
							    boolean isProject=curDto.type == Constants.DiscoverProjectIntent;
 								Intent intent = new Intent(User_my_publish.this,isProject ? Discover_publishprojectActivity.class
										                                                  : Discover_pubishmoneyActivity.class);
 								intent.putExtra("jsonObj", strObj);
 								intent.putExtra("isModify", true);
								User_my_publish.this.startActivityForResult(intent, 100);
 						 
							}
						}, 10);
					break;
				  case 1:
						IntentionDto  curDto= usermyPublishAdapter.getAt(position);
						if(curDto.projectId!= null&&curDto.projectId>0){
							CommonUtil.showToast(R.string.public_detail_operation_fail, User_my_publish.this);
							return;
						}
					  
					  myhandler.postDelayed(new Runnable() {
							@Override
							public void run() {
								// TODO Auto-generated method stub
					 			long  curId= usermyPublishAdapter.getAt(position).id;
 								//delAttention(curId); 
					 			curAction=ActionType.DeleteIntent;
					 			mZrbRestClient.sessionGet("intention/delete?id="+curId);
							}
						}, 10);
					break;
				}
 				//return index==1 ?true:false;
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data){
 	 
		if(resultCode==Activity.RESULT_OK){
			if(requestCode==100){
 				String callBackStr=data.getStringExtra("jsonStr");
 				
 				CommonUtil.InfoLog("callBackStr",callBackStr);
				Gson gson = new Gson();  
 				IntentionDto curDto=gson.fromJson(callBackStr, IntentionDto.class);
  				
 				usermyPublishAdapter.removeAt(curEditPostion);
 				usermyPublishAdapter.list1.add(curEditPostion, curDto);
 				usermyPublishAdapter.notifyDataSetChanged();
   			}
 		}
 		super.onActivityResult(requestCode, resultCode, data);
	}
	
	

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_left_root:
			this.finish();
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Intent intent;
		int index=position-1;
		IntentionDto intentionDto = usermyPublishAdapter.list1.get(index);
		if (intentionDto.projectId != null) {
			intent = new Intent(User_my_publish.this,
					ProjectDetailActivity.class);
			intent.putExtra("id", intentionDto.projectId);
			intent.putExtra("title", intentionDto.intro);
			intent.putExtra("from", "2");
			intent.putExtra("position", index);
			startActivity(intent);
			
		} else {
			if (intentionDto.type == Constants.DiscoverProjectIntent) {
				intent = new Intent(User_my_publish.this,
						DiscoverDetailOneActivity.class);
				intent.putExtra("id",intentionDto.id);
				intent.putExtra("attentionTimes", intentionDto.attentionTimes);
				intent.putExtra("messageAmount", intentionDto.messageAmount);
				intent.putExtra("position", index);
				intent.putExtra("from", "2");
				intent.putExtra("attention", intentionDto.attention);
				User_my_publish.this.startActivity(intent);
				
			} else if (intentionDto.type == Constants.DiscoverMoneyIntent) {
				intent = new Intent(User_my_publish.this,
						MoneyDetailActivity.class);
				intent.putExtra("id", intentionDto.projectId);
				intent.putExtra("title", intentionDto.intro);
				intent.putExtra("from", "2");
				intent.putExtra("position", index);
				startActivity(intent);
			}

		}

		/*
		 * Intention intention = list.get(position-1); if( 101 ==
		 * intention.type){ //101 项目意向 跳转
		 * 
		 * }else{ //102资金意向 跳转
		 * 
		 * }
		 */
		// Toast.makeText(this, "点击事件", 0).show();
	}

	private void showloading() {
		if (progTip == null)
			progTip = ProgressDialogEx.Show(this, " title", "正在加载中...", true,
					true);
		else
			progTip.Show("正在加载中...");
	}
	
	private void hideloading(){
		
		if (progTip != null) progTip.Dismiss();
	}
	
	ZrbRestClient mZrbRestClient;
	private void LoadData(long maxId, final boolean isreflesh) {
		
		curAction=ActionType.LoadData;
		RequestParams param = new RequestParams();
		//param.put("zrb_front_ut", AppSetting.curUser.zrb_front_ut);
		param.put("limit", 14);
 		if (maxId != -1) {
			param.put("maxId", maxId);
		}
 		mZrbRestClient.post("ucenter/findPublish", param);
	}

	
    /** List点击时会发送些事件，接收到事件后更新详情 */
    public void onEventMainThread(BaseEvent event) {
    	
		if (event instanceof FavorEvent) {
 			FavorEvent item = (FavorEvent) event;
			int pos = item.postion;
			usermyPublishAdapter.list1.get(pos).attentionTimes += item.isAdd ? 1 : -1;
			usermyPublishAdapter.list1.get(pos).attention = item.isAdd ? 1 : 0;
			usermyPublishAdapter.notifyDataSetChanged();
		}
		else if(event instanceof MessageEvent){
			
			MessageEvent item = (MessageEvent) event;
			int pos = item.postion;
			usermyPublishAdapter.list1.get(pos).messageAmount+=1; 
			usermyPublishAdapter.notifyDataSetChanged();
		}
      
     }
	
 
	public void registerBoradcastReceiver1() {
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(Constants.FocusNum_PUBLISE_mainlist);
		// 注册广播
		registerReceiver(mBroadcastReceiver1, myIntentFilter);
	}
	 
	private BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {

			String action = intent.getAction();
			if (action.equals(Constants.FocusNum_PUBLISE_mainlist)) {
				String from = intent.getStringExtra("from");
				int position = intent.getIntExtra("position", -1);
				if ("2".equals(from)) {
					addCount(position);
				}
				 
			}

		}
	};

	
	
	
	protected void addCount(int position) {
		// int position = data.getIntExtra("position", -1);
		// TODO Auto-generated method stub
		usermyPublishAdapter.list1.get(position).messageAmount = usermyPublishAdapter.list1
				.get(position).messageAmount + 1;
		usermyPublishAdapter.notifyDataSetChanged();
	}
  

	@Override
	 public void onRefresh() {
		
		 currentPage=1;
		 myhandler.postDelayed(new Runnable() {
	            @Override
	            public void run() {
                    mListView.setRefreshTime(CommonUtil.getcurTime(User_my_publish.this));
	                LoadData(-1, true);
	            }
	        }, 500);
	    }
 	
	@Override
    public void onLoadMore() {
		currentPage++;
 		myhandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				
				LoadData(usermyPublishAdapter.getMinId(), false);
			}
		}, 500);
		
	}
 
	
	
}
